package org.ws.httphelper.support.pipeline.handler.response;

import com.alibaba.fastjson.JSON;
import org.ws.httphelper.common.XmlUtil;
import org.ws.httphelper.core.pipeline.HandlerOrder;
import org.ws.httphelper.core.pipeline.ResponseHandler;
import org.ws.httphelper.exception.ParseException;
import org.ws.httphelper.exception.ResponseException;
import org.ws.httphelper.model.RequestContext;
import org.ws.httphelper.model.http.ResponseData;
import org.ws.httphelper.model.http.ResponseFuture;
import org.ws.httphelper.model.http.ResponseType;

import java.util.Map;

@HandlerOrder(1)
public class ParseXmlHandler implements ResponseHandler {
    @Override
    public boolean handler(RequestContext requestContext) throws ResponseException {
        ResponseFuture responseFuture = requestContext.getResponseFuture();
        if (responseFuture == null
                || responseFuture.getResponseType() != ResponseType.XML) {
            return true;
        }
        Class outputClass = requestContext.getOutputClass();
        // 默认转化成map
        if(outputClass == null){
            outputClass = Map.class;
        }
        if(responseFuture.isSuccess()){
            ResponseData response = responseFuture.getResponse();
            String xml = (String) response.getBody();
            try {
                // 将xml转化成map
                Map<String, Object> map = XmlUtil.xmlToMap(xml);
                // 转化成json
                String json = JSON.toJSONString(map);
                // 转化成object
                Object output = JSON.parseObject(json, outputClass);
                responseFuture.setOutput(output);
            } catch (ParseException e) {
                throw new ResponseException(e.getMessage(),e);
            }

        }
        return true;
    }

}
